package com.ronghuanet.user.service.impl;

import com.ronghuanet.basic.util.AjaxResult;
import com.ronghuanet.basic.util.MD5Utils;
import com.ronghuanet.user.domain.Logininfo;
import com.ronghuanet.user.dto.AccountLoginDto;
import com.ronghuanet.user.mapper.LogininfoMapper;
import com.ronghuanet.user.service.ILogininfoService;
import com.ronghuanet.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-09-15
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult loginAccount(AccountLoginDto accountLoginDto) {
        String username = accountLoginDto.getUsername();
        String password = accountLoginDto.getPassword();
        Integer loginType = accountLoginDto.getLoginType();

        //1 null校验
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)||loginType==null)
            return AjaxResult.me().setSuccess(false).setMessage("非法请求,参数异常！");

        //2 通过username，从数据库中查询登录信息
        Logininfo logininfo = logininfoMapper
                .loadUserByAccount(accountLoginDto);
        //3 登录实现
        //3.1 登录信息不存在
        if (logininfo==null)
            return AjaxResult.me().setSuccess(false).setMessage("用户名或密码不正确！");
        //3.2 登录信息状态十分禁用
        if (logininfo.getDisable()==0)
            return AjaxResult.me().setSuccess(false).setMessage("账号已经禁用，请求联系客服！");
        //3.3 验证密码十分正确
        String salt = logininfo.getSalt();
        String inputSecurityPwd = MD5Utils.encrypByMd5(password + salt);
        if (!logininfo.getPassword().equals(inputSecurityPwd))
            return AjaxResult.me().setSuccess(false).setMessage("用户名或密码不正确！");

        //4 token操作
        //4.1 通过uuid产生一个token
        String token = UUID.randomUUID().toString();
        //4.2 以token作为key存在用户信息和权限信息
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //5 返回token和用户信息->map(token-值，user-User对象)
        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        logininfo.setPassword(null); //不要把敏感信息返回前台
        logininfo.setSalt(null);
        result.put("loginInfo",logininfo);
        return AjaxResult.me().setResult(result);
    }
}
